package io.renren.modules.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zheok.testing.vo.CatagoryVo;
import io.renren.modules.app.service.CatagoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.zheok.testing.dao.CatagoryDao;
import com.zheok.testing.entity.CatagoryEntity;


@Service("catagoryService")
public class CatagoryServiceImpl extends ServiceImpl<CatagoryDao, CatagoryEntity> implements CatagoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CatagoryEntity> page = this.page(
                new Query<CatagoryEntity>().getPage(params),
                new QueryWrapper<CatagoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CatagoryVo> tree() {
        //拿到所有分类
        List<CatagoryEntity> all = this.list();
        List<CatagoryVo> collect = all.stream().filter(i -> i.getParentId().equals("0")).map(item -> {
            CatagoryVo catagoryVo = new CatagoryVo();
            //开始收集1级分类
            BeanUtils.copyProperties(item, catagoryVo);
            catagoryVo.setLabel(item.getCatagoryName());
            catagoryVo.setLables(item.getLabel());
            catagoryVo.setValue(item.getId());
            catagoryVo.setChildren(getchildren(item, all));//递归方法
            return catagoryVo;
        }).collect(Collectors.toList());
        return collect;
    }

    private List<CatagoryVo> getchildren(CatagoryEntity root, List<CatagoryEntity> all) {
        List<CatagoryVo> collect = all.stream().filter(fitem -> fitem.getParentId().equals(root.getId() )
        ).map(item -> {
            CatagoryVo catagoryVo = new CatagoryVo();
            BeanUtils.copyProperties(item, catagoryVo);
            if(item.getParentId().equals(root.getId())){
                catagoryVo.setChildren(getchildren(item, all)==null?null:getchildren(item, all));//递归方法
            }
            catagoryVo.setValue(item.getId());    catagoryVo.setLables(item.getLabel());
            catagoryVo.setLabel(item.getCatagoryName());
            return catagoryVo;
        }).collect(Collectors.toList());
        return collect;

    }

}